// mythread.cpp : 定义控制台应用程序的入口点。
//
#include <iostream>
#include <thread>
#include <mutex>
#include <fstream>
#include <deque>
#include <condition_variable>
using namespace std;

mutex m_mutex;
condition_variable cond;

deque<int> q;

void shared_print(string msg, int id)
{
	//m_mutex.lock();
	lock_guard<mutex> guard(m_mutex);
	cout << msg.c_str() << id << endl;
	//m_mutex.unlock();
}

void function_1()
{
	int count = 1000;
	while (count > 0)
	{
		unique_lock<mutex> locker(m_mutex);
		q.push_back(count);
		locker.unlock();
		cond.notify_one();
		this_thread::sleep_for(chrono::seconds(1));
		count--;
	}
}

void function_2()
{
	int data = 0;
	while (data != 1)
	{
		unique_lock<mutex> locker(m_mutex);
		cond.wait(locker, []() { return !q.empty(); });
		data = q.back();
		q.pop_back();
		locker.unlock();
		cout << "t2 got a value from t1: " << data << endl;
	}
}

int main()
{
	// thread t1(function_1);
	// thread t2(function_2);

	// t1.join();
	// t2.join();

	for (int i = 0; i < 1000; i++)
	{
		cout << "t2 got a value from t1: " << i << endl;
		this_thread::sleep_for(chrono::seconds(5));
	}
	getchar();
	return 0;
}
